<template>
	<div class="batch-edit-modal">
		<a-modal v-model:open="visible" title="批量编辑图片" :footer="false" @cancel="closeModal" width="600px">
			<a-typography-paragraph type="secondary">* 只对当前页面的图片生效</a-typography-paragraph>

			<a-form layout="vertical" name="batchEditForm" :model="formData" @finish="handleSubmit">
				<a-form-item name="category" label="分类">
					<a-auto-complete
						v-model:value="formData.category"
						placeholder="输入分类"
						:options="filteredCategoryOptions"
						allow-clear
						@search="onCategorySearch"
						@select="onCategorySelect"
					/>
				</a-form-item>

				<a-form-item name="tags" label="标签">
					<a-select
						v-model:value="formData.tags"
						mode="multiple"
						placeholder="选择标签"
						:options="filteredTagOptions"
						allow-clear
						show-search
						:filter-option="false"
						@search="onTagSearch"
						@select="onTagSelect"
						@deselect="onTagDeselect"
					/>
				</a-form-item>

				<a-form-item name="nameRule" label="命名规则">
					<a-auto-complete
						v-model:value="formData.nameRule"
						placeholder="输入命名规则，例如：图片{序号} 或 照片{序号}"
						:options="nameRuleOptions"
						allow-clear
						@select="onNameRuleSelect"
					/>
					<div style="font-size: 12px; color: #666; margin-top: 4px">
						说明：使用 {序号} 作为占位符，系统会自动替换为递增数字
					</div>
					<div
						v-if="formData.nameRule && formData.nameRule.includes('{序号}')"
						style="font-size: 12px; color: #1890ff; margin-top: 4px"
					>
						预览效果：{{ getNameRulePreview() }}
					</div>
				</a-form-item>

				<a-form-item>
					<a-space style="width: 100%; justify-content: flex-end">
						<a-button @click="closeModal">取消</a-button>
						<a-button type="primary" html-type="submit" :loading="loading">提交</a-button>
					</a-space>
				</a-form-item>
			</a-form>
		</a-modal>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { editPictureByBatchUsingPost, listPictureTagCategoryUsingGet } from '@/api/pictureController'

interface Props {
	pictureIdList?: number[]
	spaceId?: number
}

const props = withDefaults(defineProps<Props>(), {
	pictureIdList: () => [],
	spaceId: undefined,
})

// 定义事件
const emit = defineEmits<{
	success: []
}>()

const visible = ref<boolean>(false)
const loading = ref<boolean>(false)

// 表单数据
const formData = reactive<API.PictureEditByBatchRequest>({
	category: '',
	tags: [],
	nameRule: '',
	pictureIdList: [],
	spaceId: undefined,
})

// 分类和标签选项
const categoryOptions = ref<{ value: string; label: string }[]>([])
const tagOptions = ref<{ value: string; label: string }[]>([])
const filteredCategoryOptions = ref<{ value: string; label: string }[]>([])
const filteredTagOptions = ref<{ value: string; label: string }[]>([])

// 命名规则预设选项
const nameRuleOptions = ref<{ value: string; label: string }[]>([
	{ value: '图片{序号}', label: '图片{序号} - 例如：图片1、图片2、图片3...' },
	{ value: '照片{序号}', label: '照片{序号} - 例如：照片1、照片2、照片3...' },
	{ value: 'IMG_{序号}', label: 'IMG_{序号} - 例如：IMG_1、IMG_2、IMG_3...' },
	{ value: 'picture_{序号}', label: 'picture_{序号} - 例如：picture_1、picture_2、picture_3...' },
	{ value: '我的图片{序号}', label: '我的图片{序号} - 例如：我的图片1、我的图片2、我的图片3...' },
])

// 搜索关键词
const categorySearchValue = ref('')
const tagSearchValue = ref('')

// 防抖定时器
let categorySearchTimer: number | null = null
let tagSearchTimer: number | null = null

const openModal = () => {
	visible.value = true
	// 重置表单数据
	formData.category = ''
	formData.tags = []
	formData.nameRule = ''
	formData.pictureIdList = props.pictureIdList
	formData.spaceId = props.spaceId
}

const closeModal = () => {
	visible.value = false
	// 清除搜索状态
	categorySearchValue.value = ''
	tagSearchValue.value = ''
}

// 分类搜索（带防抖）
const onCategorySearch = (searchText: string) => {
	categorySearchValue.value = searchText

	// 清除之前的定时器
	if (categorySearchTimer) {
		clearTimeout(categorySearchTimer)
	}

	// 设置新的防抖定时器
	categorySearchTimer = setTimeout(() => {
		filterCategoryOptions(searchText)
	}, 300)
}

// 过滤分类选项
const filterCategoryOptions = (searchText: string) => {
	if (!searchText) {
		filteredCategoryOptions.value = categoryOptions.value
	} else {
		const searchLower = searchText.toLowerCase()
		filteredCategoryOptions.value = categoryOptions.value.filter((option) => {
			return option.label.toLowerCase().includes(searchLower) || option.value.toLowerCase().includes(searchLower)
		})
	}
}

// 分类选择
const onCategorySelect = (value: string) => {
	formData.category = value
	categorySearchValue.value = ''
}

// 标签搜索（带防抖）
const onTagSearch = (searchText: string) => {
	tagSearchValue.value = searchText

	// 清除之前的定时器
	if (tagSearchTimer) {
		clearTimeout(tagSearchTimer)
	}

	// 设置新的防抖定时器
	tagSearchTimer = setTimeout(() => {
		filterTagOptions(searchText)
	}, 300)
}

// 过滤标签选项
const filterTagOptions = (searchText: string) => {
	if (!searchText) {
		filteredTagOptions.value = tagOptions.value
	} else {
		const searchLower = searchText.toLowerCase()
		filteredTagOptions.value = tagOptions.value.filter(
			(option) => option.label.toLowerCase().includes(searchLower) || option.value.toLowerCase().includes(searchLower)
		)
	}
}

// 标签选择
const onTagSelect = (value: string) => {
	tagSearchValue.value = ''
}

// 标签取消选择
const onTagDeselect = (value: string) => {
	if (tagSearchValue.value === value) {
		tagSearchValue.value = ''
	}
}

// 命名规则选择
const onNameRuleSelect = (value: string) => {
	formData.nameRule = value
}

// 获取命名规则预览
const getNameRulePreview = () => {
	if (!formData.nameRule || !formData.nameRule.includes('{序号}')) {
		return ''
	}
	const example1 = formData.nameRule.replace('{序号}', '1')
	const example2 = formData.nameRule.replace('{序号}', '2')
	const example3 = formData.nameRule.replace('{序号}', '3')
	return `${example1}、${example2}、${example3}...`
}

// 获取分类和标签选项
const getTagCategoryOptions = async () => {
	try {
		const res = await listPictureTagCategoryUsingGet()

		if (res.data.code === 0 && res.data.data) {
			// 设置分类选项
			categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => ({
				value: data,
				label: data,
			}))

			// 设置标签选项
			tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => ({
				value: data,
				label: data,
			}))

			// 初始化过滤选项为全部选项
			filteredCategoryOptions.value = [...categoryOptions.value]
			filteredTagOptions.value = [...tagOptions.value]
		} else {
			message.error('获取分类标签列表失败: ' + res.data.message)
		}
	} catch (error) {
		message.error('获取分类标签列表失败，请重试')
	}
}

// 提交表单
const handleSubmit = async () => {
	if (!formData.pictureIdList || formData.pictureIdList.length === 0) {
		message.error('请选择要编辑的图片')
		return
	}

	// 检查是否至少填写了一个字段
	if (!formData.category && (!formData.tags || formData.tags.length === 0) && !formData.nameRule) {
		message.error('请至少填写一个编辑字段')
		return
	}

	// 验证命名规则格式
	if (formData.nameRule && !formData.nameRule.includes('{序号}')) {
		message.error('命名规则必须包含 {序号} 占位符，例如：图片{序号}')
		return
	}

	loading.value = true
	try {
		const res = await editPictureByBatchUsingPost(formData)

		if (res.data.code === 0) {
			message.success('批量编辑成功！')
			closeModal()
			emit('success')
		} else {
			message.error('批量编辑失败: ' + res.data.message)
		}
	} catch (error) {
		message.error('批量编辑失败，请重试')
	} finally {
		loading.value = false
	}
}

// 页面加载时获取分类和标签选项
onMounted(() => {
	getTagCategoryOptions()
})

// 暴露函数给父组件
defineExpose({
	openModal,
})
</script>

<style scoped lang="scss">
.batch-edit-modal {
	:deep(.ant-form-item) {
		margin-bottom: 16px;
	}

	:deep(.ant-form-item-label) {
		font-weight: 500;
		color: #333;
	}

	:deep(.ant-select),
	:deep(.ant-input),
	:deep(.ant-auto-complete) {
		width: 100%;
	}

	:deep(.ant-typography) {
		margin-bottom: 16px;
	}
}
</style>
